#include "ServerSocket.h"
#include "ConnectionPOP3.h"
#include "ConnectionSMTP.h"
#include "ConnectionControl.h"
#include <boost\bind.hpp>


using namespace boost::asio;


ServerSocket::ServerSocket(int p, string servername):waitForConnection(true), port(p), name(servername)
{
}

ServerSocket::ServerSocket(string servername):port(0), waitForConnection(false), name(servername)
{
}

ServerSocket::~ServerSocket(void)
{
	waitForConnection = false;
	threads.join_all();
}

void ServerSocket::setPort(int p)
{
	port = p;
	waitForConnection = true;
}

void ServerSocket::startConnection(tcp::socket* socket)
{
		if(port == 25)
		{
			ConnectionSMTP smtp(socket, name);
			//threads.create_thread(boost::bind(&ConnectionSMTP::run, &smtp));
			smtp.run();
		}
		if(port == 110)
		{
			ConnectionPOP3 pop(socket);
			//threads.create_thread(boost::bind(&ConnectionPOP3::run, &pop));
			pop.run();
		} 
		if(port == 8000)
		{
			ConnectionControl control(socket);
			//threads.create_thread(boost::bind(&ConnectionControl::run, &control));
			control.run();
		}
}

// Startet den Socket
void ServerSocket::run()
{
	if(port < 1)
	{
		return;
	}
	
	int count = 0;
	
	io_service ioService;
	tcp::acceptor acceptor(ioService, tcp::endpoint(tcp::v4(), port));


	while(waitForConnection)
	{
		
		tcp::socket* socket = new tcp::socket(ioService);
		//tcp::socket socket(ioService);
		cout << "Warte auf Verbindung auf Port " << port << endl;
		// Wartet auf eine Verbindung
		acceptor.accept(*socket);
		cout << "Verbindung erhalten auf Port " << port << endl;
		startConnection(socket);

		//only test
		//boost::this_thread::sleep(boost::posix_time::seconds(2));

	}
	threads.join_all();
}